<template>
  <div class="supplier-return-page">
    <el-card shadow="never" class="breadcrumb-card">
      <div class="breadcrumb-content">
        <div class="breadcrumb-title">
          <div class="breadcrumb-icon-wrapper">
            <el-icon class="breadcrumb-icon">
              <Box />
            </el-icon>
          </div>
          <div>
            <p class="breadcrumb-subtitle">仓库管理 · 供应商退货</p>
            <h2 class="breadcrumb-heading">供应商退货管理</h2>
          </div>
        </div>
        <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb-nav">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
          <el-breadcrumb-item>供应商退货</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-card>

    <el-card shadow="never" class="search-card">
      <div class="search-header">
        <div class="search-title">
          <div class="search-title-left">
            <div class="search-icon-wrapper">
              <el-icon class="search-title-icon"><Search /></el-icon>
            </div>
            <div>
              <h3 class="search-title-text">筛选查询</h3>
              <p class="search-hint">支持关键字、日期与供应商组合查询</p>
            </div>
          </div>
          <div class="search-header-actions">
            <el-button
              text
              type="primary"
              @click="toggleSearchExpand"
              class="expand-btn"
            >
              <el-icon>
                <ArrowDown v-if="!searchExpanded" />
                <ArrowUp v-else />
              </el-icon>
              {{ searchExpanded ? "收起" : "展开" }}
            </el-button>
          </div>
        </div>
      </div>
      <el-collapse-transition>
        <div v-show="searchExpanded">
          <el-form :model="searchForm" class="search-form" label-position="top">
            <div class="search-form-grid">
              <el-form-item label="退货编号/名称" class="search-form-item">
                <el-input
                  v-model="searchForm.returnCodeName"
                  placeholder="请输入退货编号或名称进行搜索"
                  clearable
                  class="search-input"
                  @keyup.enter="handleSearch"
                >
                  <template #prefix>
                    <el-icon class="input-icon"><Search /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="采购单号/名称" class="search-form-item">
                <el-input
                  v-model="searchForm.purchaseCodeName"
                  placeholder="请输入采购单号或名称进行搜索"
                  clearable
                  class="search-input"
                  @keyup.enter="handleSearch"
                >
                  <template #prefix>
                    <el-icon class="input-icon"><Document /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="退货日期" class="search-form-item">
                <el-date-picker
                  v-model="searchForm.returnDate"
                  type="date"
                  placeholder="请选择退货日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  clearable
                  class="search-input date-picker"
                  :prefix-icon="Calendar"
                />
              </el-form-item>
              <el-form-item label="供应商" class="search-form-item">
                <el-input
                  v-model="searchForm.supplier"
                  placeholder="请输入供应商名称进行搜索"
                  clearable
                  class="search-input"
                  @keyup.enter="handleSearch"
                >
                  <template #prefix>
                    <el-icon class="input-icon"><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
            </div>
            <div class="search-actions-wrapper">
              <div class="search-actions">
                <el-button
                  @click="handleReset"
                  class="reset-btn"
                  :icon="RefreshLeft"
                  size="default"
                >
                  重置条件
                </el-button>
                <el-button
                  type="primary"
                  :loading="loading"
                  :icon="Search"
                  @click="handleSearch"
                  class="search-btn"
                  size="default"
                >
                  立即查询
                </el-button>
                <el-dropdown trigger="click" class="more-dropdown">
                  <el-button type="info" class="more-btn" :icon="More">
                    更多操作
                    <el-icon class="el-icon--right">
                      <ArrowDown />
                    </el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="handleExport" :icon="Download">
                        导出全部数据
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>

    <el-card shadow="never" class="table-card">
      <div class="table-header">
        <div class="table-title">
          <el-icon class="table-title-icon"><Box /></el-icon>
          <span>供应商退货列表</span>
          <el-tag size="small" effect="plain" class="list-tag">列表视图</el-tag>
          <el-tag
            v-if="multipleSelection.length > 0"
            size="small"
            type="info"
            class="selection-tag"
          >
            已选择 {{ multipleSelection.length }} 项
          </el-tag>
        </div>
        <div class="table-operations">
          <el-button
            type="primary"
            size="default"
            @click="handleAdd"
            :icon="Plus"
            class="action-btn"
          >
            新增
          </el-button>
          <el-button
            type="danger"
            size="default"
            :disabled="!multipleSelection.length"
            @click="handleBatchDelete"
            class="action-btn batch-delete-btn"
          >
            批量删除
            <template v-if="multipleSelection.length > 0">
              ({{ multipleSelection.length }})
            </template>
          </el-button>
          <el-button
            :icon="Download"
            @click="handleExport"
            :loading="exportLoading"
            class="action-btn export-btn"
          >
            导出
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        stripe
        border
        class="data-table"
        :row-class-name="tableRowClassName"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          type="index"
          label="序号"
          width="70"
          align="center"
          :index="getIndex"
        >
          <template #default="{ $index }">
            <span class="index-number">{{ getIndex($index) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="returnOrderName"
          label="退货单名称"
          min-width="160"
        >
          <template #default="scope">
            <span class="table-cell-primary">{{
              scope.row.returnOrderName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="returnOrderNo"
          label="退货单编号"
          min-width="160"
        >
          <template #default="scope">
            <el-tag size="small" effect="plain" type="info" class="code-tag">
              {{ scope.row.returnOrderNo }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="returnDate" label="退货日期" min-width="130">
          <template #default="{ row }">
            <span class="table-cell-time">{{
              formatDate(row.returnDate)
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="purchaseOrderName"
          label="采购单名称"
          min-width="150"
        >
          <template #default="scope">
            <span class="table-cell-text">{{
              scope.row.purchaseOrderName
            }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="purchaseOrderNo"
          label="采购单号"
          min-width="150"
        >
          <template #default="scope">
            <el-tag
              size="small"
              effect="plain"
              type="warning"
              v-if="scope.row.purchaseOrderNo"
            >
              {{ scope.row.purchaseOrderNo }}
            </el-tag>
            <span v-else class="table-cell-empty">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="supplier" label="供应商" min-width="150">
          <template #default="scope">
            <div class="table-cell-user">
              <el-icon class="user-icon"><User /></el-icon>
              <span>{{ scope.row.supplier || "-" }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="returnQuantity"
          label="退货总数"
          min-width="110"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              size="small"
              effect="plain"
              type="success"
              class="quantity-tag"
            >
              {{ row.returnQuantity ?? 0 }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="stats"
          label="退货状态"
          min-width="110"
          align="center"
        >
          <template #default="{ row }">
            <el-tag
              v-if="row.stats === 0"
              size="small"
              effect="plain"
              type="warning"
              class="status-tag"
            >
              未退货
            </el-tag>
            <el-tag
              v-else-if="row.stats === 1"
              size="small"
              effect="plain"
              type="success"
              class="status-tag"
            >
              已退货
            </el-tag>
            <span v-else class="table-cell-empty">-</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="remarks"
          label="备注"
          min-width="150"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <span class="table-cell-text">{{ row.remarks || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button
                v-if="row.stats === 0"
                type="success"
                link
                size="small"
                :loading="returnLoading === row.id"
                :disabled="returnLoading !== null"
                @click="handleReturn(row)"
                class="action-link-btn return-btn"
                >退货</el-button
              >
              <el-button
                v-if="row.stats === 1"
                type="warning"
                link
                size="small"
                :loading="recallLoading === row.id"
                :disabled="recallLoading !== null"
                @click="handleRecall(row)"
                class="action-link-btn recall-btn"
                >撤回</el-button
              >
              <template v-if="row.stats === 0 || row.stats === 1">
                <el-divider direction="vertical" />
              </template>
              <el-button
                type="primary"
                link
                size="small"
                @click="handleEdit(row)"
                class="action-link-btn edit-btn"
                >编辑</el-button
              >
              <el-divider direction="vertical" />
              <el-button
                type="danger"
                link
                size="small"
                @click="handleDelete(row)"
                class="action-link-btn delete-btn"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty-state">
            <div class="empty-icon-wrapper">
              <el-icon class="empty-icon"><Box /></el-icon>
            </div>
            <p class="empty-text">暂无供应商退货数据</p>
            <p class="empty-hint">
              您可以点击上方"新增"按钮创建新的供应商退货单
            </p>
            <el-button
              type="primary"
              :icon="Plus"
              @click="handleAdd"
              class="empty-action-btn"
              >立即创建退货单</el-button
            >
          </div>
        </template>
      </el-table>
      <div class="table-pagination">
        <div class="pagination-wrapper">
          <div class="pagination-info">
            <div class="pagination-info-item">
              <el-icon class="info-icon"><Document /></el-icon>
              <span class="pagination-text">
                共
                <strong class="highlight-number">{{
                  pagination.totalCount
                }}</strong>
                条记录
              </span>
            </div>
            <div class="pagination-info-item" v-if="pagination.totalCount > 0">
              <el-icon class="info-icon"><FolderOpened /></el-icon>
              <span class="pagination-text">
                第
                <strong class="highlight-number">{{
                  pagination.pageIndex
                }}</strong>
                /
                <strong class="highlight-number">{{
                  pagination.pageCount
                }}</strong>
                页
              </span>
            </div>
            <div class="pagination-info-item" v-if="tableData.length > 0">
              <el-icon class="info-icon"><View /></el-icon>
              <span class="pagination-text">
                显示
                <strong class="highlight-number">{{
                  (pagination.pageIndex - 1) * pagination.pageSize + 1
                }}</strong>
                -
                <strong class="highlight-number">{{
                  Math.min(
                    pagination.pageIndex * pagination.pageSize,
                    pagination.totalCount
                  )
                }}</strong>
                条
              </span>
            </div>
          </div>
          <div class="pagination-controls">
            <div class="pagination-buttons">
              <el-button
                size="default"
                @click="gotoFirst"
                :disabled="pagination.pageIndex === 1"
                class="pagination-btn first-btn"
                :icon="DArrowLeft"
              >
                首页
              </el-button>
              <el-button
                size="default"
                @click="gotoPrev"
                :disabled="pagination.pageIndex === 1"
                class="pagination-btn prev-btn"
                :icon="ArrowLeft"
              >
                上一页
              </el-button>
            </div>
            <el-pagination
              v-model:current-page="pagination.pageIndex"
              v-model:page-size="pagination.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="pagination.totalCount"
              :page-count="pagination.pageCount"
              background
              layout="sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              class="custom-pagination"
            />
            <div class="pagination-buttons">
              <el-button
                size="default"
                @click="gotoNext"
                :disabled="pagination.pageIndex >= pagination.pageCount"
                class="pagination-btn next-btn"
              >
                下一页
                <el-icon><ArrowRight /></el-icon>
              </el-button>
              <el-button
                size="default"
                @click="gotoLast"
                :disabled="pagination.pageIndex >= pagination.pageCount"
                class="pagination-btn last-btn"
              >
                尾页
                <el-icon><DArrowRight /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {
  ArrowRight,
  Box,
  Search,
  Calendar,
  Plus,
  Download,
  RefreshLeft,
  ArrowDown,
  ArrowUp,
  ArrowLeft,
  DArrowLeft,
  DArrowRight,
  User,
  Document,
  More,
  FolderOpened,
  View,
} from "@element-plus/icons-vue";
import { onMounted, reactive, ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import https from "@/Http/http";
import moment from "moment";

const router = useRouter();

// 接口定义
interface SupplierReturnDto {
  id: number;
  returnOrderNo: string;
  returnOrderName: string;
  returnDate?: string;
  purchaseOrderName: string;
  purchaseOrderNo: string;
  supplier: string;
  remarks?: string;
  stats: number;
  returnId: number;
  materialNo?: string;
  materialName?: string;
  specification?: string;
  unit?: string;
  batchNo?: string;
  returnQuantity: number;
  warehouseName?: string;
  storageAreaName?: string;
  storageLocationName?: string;
  principal?: string;
}

// API响应接口
interface ApiPageingResponse<T> {
  code: number;
  msg: string;
  data: T[];
  totalCount: number;
  pageCount: number;
}

onMounted(() => {
  loadSupplierReturnList();
});

const tableData = ref<SupplierReturnDto[]>([]);
const loading = ref(false);
const multipleSelection = ref<SupplierReturnDto[]>([]);
const searchExpanded = ref(true);
const returnLoading = ref<number | null>(null);
const recallLoading = ref<number | null>(null);

const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  pageCount: 0,
});

const searchForm = reactive({
  returnCodeName: "",
  purchaseCodeName: "",
  returnDate: null as string | null,
  supplier: "",
});

// 序号计算
const getIndex = (index: number) => {
  return (pagination.pageIndex - 1) * pagination.pageSize + index + 1;
};

// 日期格式化
const formatDate = (date: string | Date | null | undefined) => {
  if (!date) return "-";
  return moment(date).format("YYYY-MM-DD");
};

// 总页数
const totalPages = computed(() =>
  Math.max(1, Math.ceil(pagination.totalCount / pagination.pageSize))
);

// 加载供应商退货列表
const loadSupplierReturnList = () => {
  loading.value = true;
  const params: any = {
    PageIndex: pagination.pageIndex,
    PageSize: pagination.pageSize,
  };

  if (searchForm.returnCodeName) {
    params.ReturnCodeName = searchForm.returnCodeName.trim();
  }

  if (searchForm.purchaseCodeName) {
    params.PurchaseCodeName = searchForm.purchaseCodeName.trim();
  }

  if (searchForm.returnDate) {
    params.ReturnDate = searchForm.returnDate;
  }

  if (searchForm.supplier) {
    params.Supplier = searchForm.supplier.trim();
  }

  https.Reads.get("/Warehouse/SupplierReturnList", { params })
    .then((res: any) => {
      const responseData = res.data;

      if (responseData) {
        const code = responseData.code ?? responseData.Code;
        let dataList: any[] = [];
        let total = 0;
        let pageCount = 0;

        // 优先使用 data 字段（camelCase）
        if (responseData.data !== undefined) {
          dataList = Array.isArray(responseData.data) ? responseData.data : [];
          total = responseData.totalCount ?? 0;
          pageCount = responseData.pageCount ?? 0;
        }
        // 如果没有 data，尝试 Data 字段（PascalCase）
        else if (responseData.Data !== undefined) {
          dataList = Array.isArray(responseData.Data) ? responseData.Data : [];
          total = responseData.TotalCount ?? 0;
          pageCount = responseData.PageCount ?? 0;
        }

        if (code === -1) {
          const msg =
            responseData.msg ?? responseData.Msg ?? "获取供应商退货列表失败";
          ElMessage.error(msg);
          tableData.value = [];
          pagination.totalCount = 0;
          pagination.pageCount = 0;
        } else {
          tableData.value = dataList.map((item: SupplierReturnDto) => ({
            ...item,
            stats: item.stats ?? 0,
          }));
          pagination.totalCount = total;
          pagination.pageCount = Math.max(1, pageCount); // 确保至少为 1
        }
      } else {
        ElMessage.error("获取供应商退货列表失败：响应数据为空");
        tableData.value = [];
        pagination.totalCount = 0;
        pagination.pageCount = 0;
        pagination.pageIndex = 1;
      }
    })
    .catch((error: any) => {
      console.error("加载供应商退货列表失败:", error);
      const errorMsg =
        error?.response?.data?.msg ??
        error?.response?.data?.Msg ??
        error?.message ??
        "获取供应商退货列表失败，请稍后重试";
      ElMessage.error(errorMsg);
      tableData.value = [];
      pagination.totalCount = 0;
      pagination.pageCount = 0;
      pagination.pageIndex = 1;
    })
    .finally(() => {
      loading.value = false;
    });
};

// 查询
const handleSearch = () => {
  pagination.pageIndex = 1;
  loadSupplierReturnList();
};

// 重置
const handleReset = () => {
  searchForm.returnCodeName = "";
  searchForm.purchaseCodeName = "";
  searchForm.returnDate = null;
  searchForm.supplier = "";
  handleSearch();
};

// 每页条数改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.pageIndex = 1;
  loadSupplierReturnList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageIndex = val;
  loadSupplierReturnList();
};

// 选择改变
const handleSelectionChange = (selection: SupplierReturnDto[]) => {
  multipleSelection.value = selection;
};

// 跳转到第一页
const gotoFirst = () => {
  if (pagination.pageIndex > 1) {
    pagination.pageIndex = 1;
    loadSupplierReturnList();
  }
};

// 跳转到上一页
const gotoPrev = () => {
  if (pagination.pageIndex > 1) {
    pagination.pageIndex -= 1;
    loadSupplierReturnList();
  }
};

// 跳转到下一页
const gotoNext = () => {
  if (pagination.pageIndex < pagination.pageCount) {
    pagination.pageIndex += 1;
    loadSupplierReturnList();
  }
};

// 跳转到最后一页
const gotoLast = () => {
  if (pagination.pageIndex < pagination.pageCount) {
    pagination.pageIndex = pagination.pageCount;
    loadSupplierReturnList();
  }
};

// 切换搜索区域展开/收起
const toggleSearchExpand = () => {
  searchExpanded.value = !searchExpanded.value;
};

// 表格行类名
const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any;
  rowIndex: number;
}) => {
  if (rowIndex % 2 === 1) {
    return "table-row-even";
  }
  return "";
};

// 新增
const handleAdd = () => {
  router.push("/SupplierReturnAdd");
};

// 编辑
const handleEdit = (row: SupplierReturnDto) => {
  router.push({
    path: "/SupplierReturnAdd",
    query: { id: row.id },
  });
};

// 删除
const handleDelete = (row: SupplierReturnDto) => {
  ElMessageBox.confirm(
    `确定要删除退货单"${row.returnOrderName}"吗？`,
    "确认删除",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      https.Writes.put("/Warehouse/SupplierReturnDelete", { id: row.id })
        .then((res: any) => {
          const responseData = res.data;
          const code = responseData.code ?? responseData.Code;
          if (code === 1) {
            const msg = responseData.msg ?? responseData.Msg ?? "删除成功";
            ElMessage.success(msg);
            loadSupplierReturnList();
          } else {
            const msg = responseData.msg ?? responseData.Msg ?? "删除失败";
            ElMessage.error(msg);
          }
        })
        .catch((error: any) => {
          console.error("删除失败:", error);
          const errorMsg =
            error?.response?.data?.msg ??
            error?.response?.data?.Msg ??
            error?.message ??
            "删除失败，请稍后重试";
          ElMessage.error(errorMsg);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 退货（确认退货）
const handleReturn = (row: SupplierReturnDto) => {
  // 状态验证：只有未退货状态（0）才能执行退货操作
  if (row.stats !== 0) {
    ElMessage.warning("只有未退货状态的退货单才能执行退货操作");
    return;
  }

  ElMessageBox.confirm(
    `确定要执行退货单"${row.returnOrderName}"的退货操作吗？执行后状态将变更为已退货。`,
    "确认退货",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      returnLoading.value = row.id;
      return https.Writes.put("/Warehouse/SupplierReturnConfirm", {
        Id: row.id,
      })
        .then((res: any) => {
          const responseData = res.data;
          const code = responseData.code ?? responseData.Code;
          const msg = responseData.msg ?? responseData.Msg ?? "退货操作成功";

          if (code === 1) {
            ElMessage.success(msg);
            loadSupplierReturnList();
          } else {
            throw new Error(msg || "退货操作失败");
          }
        })
        .catch((error: any) => {
          console.error("退货操作失败:", error);
          const errorMsg =
            error?.response?.data?.msg ??
            error?.response?.data?.Msg ??
            error?.message ??
            "退货操作失败，请稍后重试";
          ElMessage.error(errorMsg);
        })
        .finally(() => {
          returnLoading.value = null;
        });
    })
    .catch(() => {
      // 用户取消确认对话框
      ElMessage.info("已取消退货操作");
    });
};

// 撤回
const handleRecall = (row: SupplierReturnDto) => {
  // 状态验证：只有已退货状态（1）才能执行撤回操作
  if (row.stats !== 1) {
    ElMessage.warning("只有已退货状态的退货单才能执行撤回操作");
    return;
  }

  ElMessageBox.confirm(
    `确定要撤回退货单"${row.returnOrderName}"吗？撤回后状态将变更为未退货。`,
    "确认撤回",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      recallLoading.value = row.id;
      return https.Writes.put("/Warehouse/SupplierReturnConfirm", {
        Id: row.id,
      })
        .then((res: any) => {
          const responseData = res.data;
          const code = responseData.code ?? responseData.Code;
          const msg = responseData.msg ?? responseData.Msg ?? "撤回操作成功";

          if (code === 1) {
            ElMessage.success(msg);
            loadSupplierReturnList();
          } else {
            throw new Error(msg || "撤回操作失败");
          }
        })
        .catch((error: any) => {
          console.error("撤回操作失败:", error);
          const errorMsg =
            error?.response?.data?.msg ??
            error?.response?.data?.Msg ??
            error?.message ??
            "撤回操作失败，请稍后重试";
          ElMessage.error(errorMsg);
        })
        .finally(() => {
          recallLoading.value = null;
        });
    })
    .catch(() => {
      // 用户取消确认对话框
      ElMessage.info("已取消撤回操作");
    });
};

// 批量删除
const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    ElMessage.warning("请选择需要删除的供应商退货单！");
    return;
  }

  const ids = multipleSelection.value.map((x) => x.id);

  ElMessageBox.confirm(
    `确认要批量删除选中的${multipleSelection.value.length}条供应商退货单吗？`,
    "警告",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      https.Writes.delete("/Warehouse/SupplierReturnDeletes", {
        data: { Ids: ids },
      })
        .then((res: any) => {
          const responseData = res.data;
          const code = responseData.code ?? responseData.Code;
          if (code === 1) {
            const msg = responseData.msg ?? responseData.Msg ?? "批量删除成功";
            ElMessage.success(msg);
            // 清空选择
            multipleSelection.value = [];
            loadSupplierReturnList();
          } else {
            const msg = responseData.msg ?? responseData.Msg ?? "批量删除失败";
            ElMessage.error(msg);
          }
        })
        .catch((error: any) => {
          console.error("批量删除失败:", error);
          const errorMsg =
            error?.response?.data?.msg ??
            error?.response?.data?.Msg ??
            error?.message ??
            "批量删除失败，请稍后重试";
          ElMessage.error(errorMsg);
        });
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 导出
const exportLoading = ref(false);
const handleExport = async () => {
  if (exportLoading.value) return;
  exportLoading.value = true;
  try {
    const params: any = {};

    // 传递查询条件
    if (searchForm.returnCodeName) {
      params.ReturnCodeName = searchForm.returnCodeName.trim();
    }

    if (searchForm.purchaseCodeName) {
      params.PurchaseCodeName = searchForm.purchaseCodeName.trim();
    }

    if (searchForm.returnDate) {
      params.ReturnDate = searchForm.returnDate;
    }

    if (searchForm.supplier) {
      params.Supplier = searchForm.supplier.trim();
    }

    const response = await https.Reads.get("/Warehouse/SupplierReturnExport", {
      params,
      responseType: "blob",
    });

    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    const timestamp = new Date()
      .toISOString()
      .replace(/[-:T]/g, "")
      .slice(0, 14);
    link.download = `供应商退货明细_${timestamp}.xlsx`;
    link.click();
    URL.revokeObjectURL(url);
    ElMessage.success("导出任务已开始，请留意下载文件");
  } catch (error: any) {
    console.error("导出供应商退货失败:", error);
    const errorMsg =
      error?.response?.data?.msg ??
      error?.response?.data?.Msg ??
      error?.message ??
      "导出供应商退货失败，请稍后重试";
    ElMessage.error(errorMsg);
  } finally {
    exportLoading.value = false;
  }
};
</script>

<style scoped lang="scss">
.supplier-return-page {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
  min-height: 100vh;

  .breadcrumb-card {
    margin-bottom: 20px;
    border-radius: 12px;
    background: #ffffff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    }

    .breadcrumb-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .breadcrumb-title {
        display: flex;
        align-items: center;
        gap: 16px;

        .breadcrumb-icon-wrapper {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 48px;
          height: 48px;
          border-radius: 12px;
          background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);

          .breadcrumb-icon {
            font-size: 24px;
            color: #ffffff;
          }
        }

        .breadcrumb-subtitle {
          margin: 0;
          font-size: 13px;
          color: #909399;
          font-weight: 400;
        }

        .breadcrumb-heading {
          margin: 4px 0 0 0;
          font-size: 22px;
          font-weight: 700;
          color: #303133;
          letter-spacing: 0.5px;
        }
      }

      .breadcrumb-nav {
        :deep(.el-breadcrumb__inner) {
          color: #606266;
          font-weight: 400;

          &.is-link {
            color: #409eff;
            transition: color 0.3s;

            &:hover {
              color: #66b1ff;
            }
          }
        }
      }
    }
  }

  .search-card {
    margin-bottom: 20px;
    border-radius: 12px;
    background: #ffffff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;
    overflow: hidden;

    &:hover {
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    }

    .search-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 24px;
      background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
      border-bottom: 2px solid #e4e7ed;

      .search-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;

        .search-title-left {
          display: flex;
          align-items: center;
          gap: 16px;

          .search-icon-wrapper {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 44px;
            height: 44px;
            border-radius: 10px;
            background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);

            .search-title-icon {
              font-size: 20px;
              color: #ffffff;
            }
          }

          .search-title-text {
            margin: 0;
            font-size: 18px;
            font-weight: 700;
            color: #303133;
            letter-spacing: 0.5px;
          }

          .search-hint {
            margin: 4px 0 0 0;
            font-size: 13px;
            color: #909399;
            font-weight: 400;
          }
        }

        .search-header-actions {
          .expand-btn {
            padding: 8px 16px;
            border-radius: 6px;
            transition: all 0.3s;

            &:hover {
              background-color: rgba(64, 158, 255, 0.1);
            }
          }
        }
      }
    }

    .search-form {
      padding: 24px;

      .search-form-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
        gap: 20px 24px;
        margin-bottom: 24px;

        .search-form-item {
          margin-bottom: 0;

          :deep(.el-form-item__label) {
            font-weight: 600;
            color: #606266;
            font-size: 14px;
            margin-bottom: 8px;
            padding: 0;
          }

          .search-input {
            width: 100%;
            transition: all 0.3s;

            :deep(.el-input__wrapper) {
              border-radius: 8px;
              box-shadow: 0 0 0 1px #dcdfe6 inset;
              transition: all 0.3s;

              &:hover {
                box-shadow: 0 0 0 1px #409eff inset;
              }

              &.is-focus {
                box-shadow: 0 0 0 1px #409eff inset,
                  0 0 0 3px rgba(64, 158, 255, 0.1);
              }
            }

            .input-icon {
              color: #909399;
              font-size: 16px;
            }

            &.date-picker {
              width: 100%;

              :deep(.el-input__wrapper) {
                border-radius: 8px;
              }
            }
          }
        }
      }

      .search-actions-wrapper {
        padding-top: 20px;
        border-top: 2px solid #f0f2f5;

        .search-actions {
          display: flex;
          justify-content: flex-end;
          align-items: center;
          gap: 12px;
          flex-wrap: wrap;

          .reset-btn {
            border-radius: 8px;
            padding: 10px 20px;
            font-weight: 500;
            transition: all 0.3s;
            border: 1px solid #dcdfe6;

            &:hover {
              background-color: #f5f7fa;
              border-color: #c0c4cc;
              transform: translateY(-1px);
            }
          }

          .search-btn {
            border-radius: 8px;
            padding: 10px 28px;
            font-weight: 600;
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
            transition: all 0.3s;

            &:hover {
              box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
              transform: translateY(-2px);
            }

            &:active {
              transform: translateY(0);
            }
          }

          .more-dropdown {
            .more-btn {
              border-radius: 8px;
              padding: 10px 20px;
              transition: all 0.3s;

              &:hover {
                background-color: #f5f7fa;
                transform: translateY(-1px);
              }
            }
          }
        }
      }
    }
  }

  .table-card {
    border-radius: 12px;
    background: #ffffff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    }

    .table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 16px;
      border-bottom: 2px solid #f0f2f5;

      .table-title {
        display: flex;
        align-items: center;
        gap: 10px;
        flex-wrap: wrap;

        .table-title-icon {
          font-size: 20px;
          color: #409eff;
        }

        span {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }

        .list-tag {
          margin-left: 8px;
          border-radius: 4px;
        }

        .selection-tag {
          margin-left: 8px;
          border-radius: 4px;
          animation: fadeIn 0.3s;
        }
      }

      .table-operations {
        display: flex;
        gap: 12px;

        .action-btn {
          border-radius: 6px;
          padding: 10px 20px;
          font-weight: 500;
          transition: all 0.3s;

          &.export-btn {
            background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
            border: none;
            color: #ffffff;
            box-shadow: 0 2px 8px rgba(103, 194, 58, 0.3);

            &:hover {
              box-shadow: 0 4px 12px rgba(103, 194, 58, 0.4);
              transform: translateY(-1px);
            }
          }

          &[type="primary"] {
            box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);

            &:hover {
              box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
              transform: translateY(-1px);
            }
          }
        }
      }
    }

    .data-table {
      :deep(.el-table__header) {
        th {
          background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
          color: #303133;
          font-weight: 600;
          border-bottom: 2px solid #ebeef5;
        }
      }

      :deep(.el-table__row) {
        transition: all 0.3s;

        &:hover {
          background-color: #f5f7fa;
          transform: scale(1.001);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        }

        &.table-row-even {
          background-color: #fafbfc;
        }
      }

      .index-number {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 28px;
        height: 28px;
        border-radius: 50%;
        background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
        color: #ffffff;
        font-weight: 600;
        font-size: 12px;
      }

      .table-cell-primary {
        color: #303133;
        font-weight: 500;
      }

      .table-cell-text {
        color: #606266;
      }

      .table-cell-time {
        color: #909399;
        font-size: 13px;
      }

      .table-cell-empty {
        color: #c0c4cc;
      }

      .table-cell-user {
        display: flex;
        align-items: center;
        gap: 6px;

        .user-icon {
          font-size: 16px;
          color: #409eff;
        }
      }

      .code-tag,
      .quantity-tag {
        border-radius: 4px;
        font-weight: 500;
      }

      .action-buttons {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 4px;

        .action-link-btn {
          padding: 4px 8px;
          border-radius: 4px;
          transition: all 0.3s;
          font-weight: 500;

          &.return-btn:hover {
            background-color: rgba(103, 194, 58, 0.1);
          }

          &.recall-btn:hover {
            background-color: rgba(230, 162, 60, 0.1);
          }

          &.edit-btn:hover {
            background-color: rgba(64, 158, 255, 0.1);
          }

          &.delete-btn:hover {
            background-color: rgba(245, 108, 108, 0.1);
          }
        }
      }
    }

    .empty-state {
      padding: 80px 20px;
      text-align: center;

      .empty-icon-wrapper {
        margin-bottom: 20px;

        .empty-icon {
          font-size: 80px;
          color: #c0c4cc;
          opacity: 0.6;
        }
      }

      .empty-text {
        margin: 0 0 8px 0;
        font-size: 16px;
        color: #606266;
        font-weight: 500;
      }

      .empty-hint {
        margin: 0 0 24px 0;
        font-size: 14px;
        color: #909399;
      }

      .empty-action-btn {
        border-radius: 6px;
        padding: 10px 24px;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
        transition: all 0.3s;

        &:hover {
          box-shadow: 0 4px 12px rgba(64, 158, 255, 0.4);
          transform: translateY(-1px);
        }
      }
    }

    .table-pagination {
      margin-top: 24px;
      padding: 20px 24px;
      background: linear-gradient(135deg, #fafbfc 0%, #f5f7fa 100%);
      border-radius: 8px;
      border: 1px solid #e4e7ed;

      .pagination-wrapper {
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 20px;

        .pagination-info {
          display: flex;
          align-items: center;
          gap: 24px;
          flex-wrap: wrap;

          .pagination-info-item {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            background: #ffffff;
            border-radius: 8px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
            transition: all 0.3s;

            &:hover {
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
              transform: translateY(-1px);
            }

            .info-icon {
              font-size: 18px;
              color: #409eff;
            }

            .pagination-text {
              font-size: 14px;
              color: #606266;
              font-weight: 500;

              .highlight-number {
                color: #409eff;
                font-weight: 700;
                font-size: 16px;
                margin: 0 2px;
              }
            }
          }
        }

        .pagination-controls {
          display: flex;
          align-items: center;
          gap: 12px;
          flex-wrap: wrap;

          .pagination-buttons {
            display: flex;
            gap: 8px;

            .pagination-btn {
              border-radius: 8px;
              padding: 8px 16px;
              font-weight: 500;
              transition: all 0.3s;
              border: 1px solid #dcdfe6;
              background: #ffffff;

              &:hover:not(:disabled) {
                background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
                color: #ffffff;
                border-color: #409eff;
                box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
                transform: translateY(-2px);
              }

              &:disabled {
                opacity: 0.5;
                cursor: not-allowed;
              }

              &.first-btn,
              &.last-btn {
                font-weight: 600;
              }
            }
          }

          .custom-pagination {
            :deep(.el-pagination__sizes) {
              .el-select {
                .el-input__wrapper {
                  border-radius: 8px;
                  box-shadow: 0 0 0 1px #dcdfe6 inset;

                  &:hover {
                    box-shadow: 0 0 0 1px #409eff inset;
                  }
                }
              }
            }

            :deep(.el-pager) {
              li {
                border-radius: 8px;
                margin: 0 4px;
                transition: all 0.3s;
                font-weight: 500;

                &.is-active {
                  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
                  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
                  color: #ffffff;
                }

                &:hover:not(.is-active) {
                  background-color: #f0f2f5;
                  transform: translateY(-1px);
                }
              }
            }

            :deep(.btn-prev),
            :deep(.btn-next) {
              border-radius: 8px;
              transition: all 0.3s;
              margin: 0 4px;

              &:hover {
                background-color: #f0f2f5;
                transform: translateY(-1px);
              }
            }

            :deep(.el-pagination__jump) {
              .el-input__wrapper {
                border-radius: 8px;
                box-shadow: 0 0 0 1px #dcdfe6 inset;

                &:hover {
                  box-shadow: 0 0 0 1px #409eff inset;
                }
              }
            }
          }
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.9);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}
</style>
